import React, { useState } from 'react';
import { Card, Typography, Form, Input, Button, Select, message, Tabs, Divider } from 'antd';
import { TranslationOutlined, ClearOutlined, CopyOutlined, CheckOutlined, DeleteOutlined, AudioOutlined, FileTextOutlined, PictureOutlined, BookOutlined, EditOutlined, UserOutlined } from '@ant-design/icons';
import { toolAPI } from '../utils/api';

const { Title, Text } = Typography;
const { Option } = Select;
const { TextArea } = Input;
const { TabPane } = Tabs;

const TranslationPage = () => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [translatedText, setTranslatedText] = useState('');
  const [isCopied, setIsCopied] = useState(false);
  const [sourceLanguage, setSourceLanguage] = useState('auto');
  const [targetLanguage, setTargetLanguage] = useState('en');
  const [showMoreInfo, setShowMoreInfo] = useState(true);

  // 支持的语言选项
  const languages = [
    { value: 'auto', label: '检测语言' },
    { value: 'zh', label: '中文' },
    { value: 'en', label: '英语' }
  ];

  // 翻译类型选项卡
  const translationTypes = [
    { key: 'text', label: '文本翻译', icon: <TranslationOutlined /> }
  ];

  // 切换源语言和目标语言
  const handleSwapLanguages = () => {
    if (sourceLanguage !== 'auto') {
      setSourceLanguage(targetLanguage);
      setTargetLanguage(sourceLanguage);
      // 如果已有翻译结果，可以交换输入和输出
      if (translatedText && form.getFieldValue('sourceText')) {
        const tempText = form.getFieldValue('sourceText');
        form.setFieldsValue({ sourceText: translatedText });
        setTranslatedText(tempText);
      }
    }
  };

  // 处理表单提交
  const handleSubmit = async (values) => {
    const { sourceText } = values;

    if (!sourceText.trim()) {
      message.error('请输入要翻译的文本');
      return;
    }

    setLoading(true);

    try {
      const response = await toolAPI.translateText({
        sourceText,
        sourceLanguage,
        targetLanguage
      });

      if (response && response.translatedText) {
        setTranslatedText(response.translatedText);
        message.success('翻译成功！');
      } else {
        message.error('翻译失败，未获取到翻译结果');
      }
    } catch (error) {
      console.error('翻译失败详细信息:', error);
      console.error('错误响应:', error.response);
      console.error('错误配置:', error.config);
      message.error(`翻译失败: ${error.response?.data?.error || '未知错误'}，详细信息请查看控制台`);
    } finally {
      setLoading(false);
    }
  };

  // 重置表单
  const handleReset = () => {
    form.resetFields();
    setTranslatedText('');
  };

  // 清空输入文本
  const handleClearInput = () => {
    form.setFieldsValue({ sourceText: '' });
  };

  // 播放语音
  const handlePlayVoice = (text, language) => {
    // 语音播放功能实现
    message.info('语音播放功能待实现');
  };

  // 展开/收起更多信息
  const toggleMoreInfo = () => {
    setShowMoreInfo(!showMoreInfo);
  };

  // 复制翻译结果
  const handleCopy = () => {
    if (translatedText) {
      navigator.clipboard.writeText(translatedText)
        .then(() => {
          setIsCopied(true);
          message.success('已复制到剪贴板');
          // 2秒后重置复制状态
          setTimeout(() => setIsCopied(false), 2000);
        })
        .catch(() => {
          message.error('复制失败，请手动复制');
        });
    }
  };

  return (
    <Card className="tool-page" style={{ width: '66.67vw', margin: '0 auto' }}>
      {/* 翻译类型选项卡 */}
      <Tabs 
        defaultActiveKey="text" 
        className="translation-tabs"
        items={translationTypes.map(type => ({
          key: type.key,
          label: <span><span className="tab-icon">{type.icon}</span>{type.label}</span>,
          children: null
        }))}
      />

      <Divider style={{ margin: '12px 0' }} />
      
      {/* 语言选择区域 */}
      <div className="language-selection">
        <Select 
          value={sourceLanguage} 
          onChange={setSourceLanguage} 
          style={{ width: '120px' }} 
          disabled={loading}
          className="language-select"
        >
          {languages.map(lang => (
            <Option key={lang.value} value={lang.value}>{lang.label}</Option>
          ))}
        </Select>
        
        <Button 
          type="text" 
          icon={<DeleteOutlined />} 
          onClick={handleSwapLanguages} 
          disabled={loading || sourceLanguage === 'auto'} 
          className="swap-button"
        />
        
        <Select 
          value={targetLanguage} 
          onChange={setTargetLanguage} 
          style={{ width: '120px' }} 
          disabled={loading}
          className="language-select"
        >
          {languages.filter(lang => lang.value !== 'auto').map(lang => (
            <Option key={lang.value} value={lang.value}>{lang.label}</Option>
          ))}
        </Select>
        
      </div>

      <div className="translation-layout">
        {/* 左侧输入区域 */}
        <div className="input-section">
          <Form
            form={form}
            layout="vertical"
            onFinish={handleSubmit}
            initialValues={{ sourceText: '你好' }}
          >
            <Form.Item
              name="sourceText"
              className="translation-input-item"
            >
              <div className="textarea-container">
                <TextArea 
                  rows={12} 
                  placeholder="请输入要翻译的文本..."
                  disabled={loading}
                  maxLength={5000}
                  showCount
                  className="translation-textarea"
                  style={{ height: '300px' }}
                />
                <div className="textarea-actions">
                  <Button type="text" icon={<ClearOutlined />} onClick={handleClearInput} disabled={loading} />
                  <Button type="text" icon={<AudioOutlined />} onClick={() => handlePlayVoice(form.getFieldValue('sourceText'), sourceLanguage)} disabled={loading} />
                </div>
              </div>
            </Form.Item>
          </Form>
        </div>

        {/* 右侧翻译结果区域 */}
        <div className="output-section">
          <div className="translation-result">
            <div className="textarea-container">
              <TextArea 
                rows={12} 
                value={translatedText} 
                readOnly 
                className="result-textarea"
                style={{ height: '280px' }}
              />
              <div className="textarea-actions">
                <Button 
                  type="text" 
                  icon={isCopied ? <CheckOutlined /> : <CopyOutlined />}
                  onClick={handleCopy}
                  disabled={!translatedText}
                  className="copy-button"
                >
                  {isCopied ? '已复制' : ''}
                </Button>
                <Button 
                  type="text" 
                  icon={<AudioOutlined />} 
                  onClick={() => handlePlayVoice(translatedText, targetLanguage)} 
                  disabled={!translatedText}
                />
              </div>
            </div>
          </div>

          {/* 翻译结果区域，简化显示 */}
        </div>
      </div>

      {/* 翻译按钮 */}
      <div className="translate-button-container">
        <Button 
          type="primary" 
          htmlType="submit" 
          loading={loading} 
          icon={<TranslationOutlined />}
          onClick={() => form.submit()}
          size="large"
          className="translate-button"
        >
          开始翻译
        </Button>
      </div>
    </Card>
  );
};

export default TranslationPage;